#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int dx[4] = { 1, -1, 0, 0 };
    int dy[4] = { 0, 0, 1, -1 };
    int cutOffTree(vector<vector<int>>& forest) {
        int ret = 0, n = forest.size(), m = forest[0].size(), aim = 0;
        queue<pair<int, int>> q;
        q.push({ 0, 0 });
        vector<int> trees;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                if (forest[i][j] > 1)
                    trees.push_back(forest[i][j]);
        sort(trees.begin(), trees.end());
        if (forest[0][0] == trees[0]) aim++;
        while (aim < trees.size()) {
            int step = 0, xx = -1, yy = -1;
            vector<vector<bool>> map(n, vector<bool>(m, false));
            cout << trees[aim] << endl;
            while (q.size()) {
                step++;
                int num = q.size();
                for (int i = 0; i < num; i++) {
                    auto [x, y] = q.front();
                    map[x][y] = true;
                    q.pop();
                    for (int k = 0; k < 4; k++) {
                        int a = x + dx[k], b = y + dy[k];
                        if (a >= 0 && a < n && b >= 0 && b < m &&
                            forest[a][b] != 0 && map[a][b] == false) {
                            if (forest[a][b] == trees[aim]) {
                                xx = a, yy = b, aim++;
                                queue<pair<int, int>> tmp;
                                tmp.push({ xx, yy });
                                q = tmp;
                                break;
                            }
                            map[a][b] = true, q.push({ a, b });
                        }
                    }
                    if (xx != -1)
                        break;
                }
                if (xx != -1) {
                    ret += step;
                    cout << step << endl;
                    break;
                }
            }
            if (xx == -1)
                return -1;
        }
        return ret;
    }
};